<template>
    <div>
        <Row v-show="_defineIdsFinished">
            <Row class-name="toolBarBox" type="flex" justify="start" class="code-row-bg" style="padding-bottom: 5px;padding-right: 10px">
                <Col span="20" push="0">
                    <slot name="toolBar"></slot>
                </Col>
                <Col span="4">
                    <div style="float: right">
                        <Tooltip class="toolBarColumnChoice" content="选择表格列" placement="bottom">
                            <Button type="primary" @click="columnChoice=true" shape="circle" icon="md-apps"></Button>
                        </Tooltip>
                    </div>
                </Col>
            </Row>
            <div class="rui-table-box">
            <Table  :loading="loading"
                   :border="border"
                   stripe
                   size="small"
                    :row-class-name="rowClassName"
                   :columns="dynamicColumns"
                   :data="tableDatas"
                   ref="ruiTable"
                   :max-height="maxHeight"
                   :width="width"
                   :height="height"
                   :show-summary="showSummary"
                   :highlight-row="true"
                   @on-select="onSelect"
                   @on-select-cancel="onSelectCancel"
                   @on-select-all="onSelectAll"
                   @on-sort-change="onSortChange"
                   @on-select-all-cancel="onSelectAllCancel"
                   @on-selection-change="onSelectionChange"
                   @on-row-click="onRowClick"
                   @on-cell-click="onCellClick"
                   @on-row-dblclick="onRowDblclick"
                   @on-current-change="onCurrentChange"
                   @on-expand="onExpand"
            >
                <slot name="header" slot="header"></slot>
                <slot name="footer" slot="footer"></slot>
                <slot name="loading" slot="loading"></slot>
            </Table>
            </div>
        </Row>
        <br>
        <Row v-if="pageAble" type="flex" justify="end" class="page">
            <Page :current="pageData.pageNumber" :transfer="true" :total="pageData.total" :page-size="pageData.pageSize" @on-change="changePage"
                  @on-page-size-change="changePageSize" :page-size-opts="pageSizeOpts" size="small" show-total
                  show-elevator show-sizer></Page>
        </Row>
        <Modal v-model="columnChoice" title="选择表格列" :footerHide="true" :styles="{top: '90px'}" >
            <CheckboxGroup title="表格列选择" v-model="columnsSelect" >
                <span v-for="(item,index) in tableColumns" :key="item.key">
                    <Checkbox style="width: 30%" :disabled="!(item.type!='selection'&&item.type!='index'&&!item._ignoreShow)"
                               :label="item.type=='selection'?'选择':item.key">{{item.type=='selection'?'选择':item.title}}</Checkbox>
                    <br v-if="(index+1)%3==0"/>
                </span>
            </CheckboxGroup>
        </Modal>
    </div>
</template>
<script>
   import ruiMixin from '../../mixin/rui-global-components';
   import ruiEleMixin from '../../mixin/rui-element-mixin'
   import col from "_c/iview/components/grid/col";
   import {deepClone} from "@/libs/utils/ObjectClone";
    export default {
        name:'rui-table',
        mixins: [ ruiMixin,ruiEleMixin ],
        props:{
            rowClassName:{
                type:Function,
                default:()=>null
            },
            defineId:{
                type:String,
                require: true
            },
            columns:{
                type: Array,
                require: false,
                default:()=>[]
            },
            select:{
                type:Boolean,
                require:false,
                default:()=>true
            },
            singleSelect:{
                type:Boolean,
                require:false,
                default:()=>false
            },
            showIndex:{
                type:Boolean,
                require:false,
                default:()=>true
            },
            fixedLeft:{
                type:Array,
                require:false,
                default:()=>{
                    return []
                }
            },
            fixedRight:{
                type:Array,
                require:false,
                default:()=>{
                    return []
                }
            },
            slots:{
                type:Array,
                require:false,
                default:()=>{
                    return []
                }
            },
            width:{
                type:[Number, String],
                require:false
            },
            height:{
                type:[Number, String],
                require:false
            },
            maxHeight:{
                type:[Number, String],
                require:false
            },
            showSummary:{
              type:Boolean,
              require:false,
              default:false
            },
            border:{
                type:Boolean,
                default:true
            },
            pageAble:{
                type:Boolean,
                require:false,
                default:true
            },
            pageSizeOpts:{
                type:Array,
                require:false,
                default:()=>[10,20,50,100]
            },
            refQuery:{
                type:String,
                require:false
            }
        },
        data(){
            return {
                pageData:{
                    pageNumber:1,
                    pageSize:10,
                    total:0
                },
                loading:false,
                tableColumns:[],
                tableDatas:[],
                columnChoice:false,
                currentIndex:0,
                columnsSelect:[],
                dynamicColumns:[],
                columnInit:false,
                sizeChanging:false
            }
        },
        computed:{
        },
        methods:{
            getPageInfo(){
                return {
                    pageNumber:this.pageData.pageNumber,
                    pageSize:this.pageData.pageSize
                }
            },
            resetPageInfo(pageNumber,pageSize){
                this.pageData.pageNumber = pageNumber;
                this.pageData.pageSize = pageSize;
                return this.getPageInfo();
            },
            calColumns(){
                let self = this;
                if(this.showIndex){
                    this.tableColumns.push({
                        type:'index',
                        indexMethod:function (row) {
                            return row._index+(self.pageData.pageNumber-1)*self.pageData.pageSize+1
                        },
                        width: 60,
                        align: "center",
                        fixed: "left",
                        _ignoreShow :true
                    });
                }
                if(this.select){
                    this.tableColumns.push({
                        type:'selection',
                        width: 60,
                        align: "center",
                        fixed: "left",
                        _ignoreShow :true
                    });
                }
                if(this.columns.length==0){
                    this.tableColumns.push(...this.clone(this.RuiPage.pageData[this.defineId].fields))
                }else{
                    this.tableColumns.push(...this.clone(this.RuiPage.pageData[this.defineId].fields.filter(value => {
                        return self.columns.includes(value.key)
                    })))
                }
                // console.log(this.tableColumns)
                this.tableColumns.forEach(value=>{
                    value._type = value.type;
                    if(!value.minWidth){
                        value.minWidth=200;
                    }
                    if(value.type!='selection'&&value.type!='index'){
                        value.type = 'String';
                    }
                    value._show = value.columnShow===undefined?true:value.columnShow;
                    if(self.fixedLeft.includes(value.key)){
                        value.fixed = 'left';
                        value._ignoreShow = true;
                    }else if(self.fixedRight.includes(value.key)){
                        value.fixed = 'right';
                        value._ignoreShow = true;
                    }else if(value.type!='selection'&&value.type!='index'&&value._show){
                        self.columnsSelect.push(value.key);
                        value._ignoreShow = false;
                    }
                    if(value.headerWidth){
                        value.width = value.headerWidth;
                    }
                    if(value.width||value.maxWidth){
                        value.tooltip = true;
                        value.ellipsis = true;
                    }
                    self.slots.forEach(slot=>{
                        if(slot.key===value.key){
                            value.render = (h, ctx)=>{
                                return h('div',self.$scopedSlots[slot.slot]({
                                    row: deepClone(ctx.row),
                                    column: ctx.column,
                                    index: ctx.index,
                                    dataDic: self._getDicData(ctx.column)
                                }));
                            }
                        }
                    })
                    if(!value.render&&value._type!='text'&&value._type!='textarea'){
                        value.render = (h,ctx)=>{
                            return h('span',self.parseSimpleStr(ctx.column,ctx.row[value.key]))
                        }
                    }
                    self.prepareDicInfo(value);
                })
                // console.log(this.tableColumns)
                this.columnInit=true;
                this.calDynamicColumn();
            },
            calDynamicColumn(){
                let self = this;
                self.columnsSelect.forEach(name=>{
                    self.tableColumns.forEach(value => {
                        if(value.key==name&&!value._ignoreShow){
                            value._show = true;
                        }else if(!value._ignoreShow&&!self.columnsSelect.includes(value.key)){
                            value._show = false;
                        }
                    })
                });
                this.dynamicColumns =  this.tableColumns.filter(value => {
                    return value._show
                })
            },
            dispatcherQuery(){
                if(this.refQuery&&this.refQuery!=''){
                    if(this.refComponent){
                        this.$emit('loadDatas', this.refComponent.getFormData());
                    }else {
                        this.$emit('loadDatas', {
                            pageNumber:this.pageData.pageNumber,
                            pageSize:this.pageData.pageSize,
                            condition: {},
                        });
                    }
                }else{
                    this.$emit('loadDatas', this.pageData.pageNumber, this.pageData.pageSize);
                }
            },
            changePage(v) {
                this.pageData.pageNumber = v;
                if(this.sizeChanging){
                    return;
                }
                this.dispatcherQuery();
                // console.log('page change')
            },
            changePageSize(v) {
                this.pageData.pageSize = v;
                this.pageData.pageNumber = 1;
                this.sizeChanging = true;
                this.dispatcherQuery();
            },
            onSelect (selection, row) {
                this.$emit('on-select', selection, row)
            },
            onSelectCancel (selection, row) {
                this.$emit('on-select-cancel', selection, row)
            },
            onSelectAll (selection) {
                this.$emit('on-select-all', selection)
            },
            onSelectAllCancel (selection) {
                this.$emit('on-select-all', selection)
            },
            onSortChange (column, key, order) {
                this.$emit('on-sort-change', column, key, order)
            },
            onSelectionChange (selection) {
                this.$emit('on-selection-change', selection)
            },
            onRowClick (row, index) {
                this.currentIndex = index;
                this.$emit('on-row-click', row, index)
            },
            onCellClick (row, column, data, event) {
                this.currentIndex = row._index;
                this.$emit('on-cell-click', row, column, data, event)
            },
            onRowDblclick (row, index) {
                this.$emit('on-row-dblclick', row, index)
            },
            onCurrentChange(currentRow,oldCurrentRow){
                this.currentIndex = currentRow._index;
                this.$emit('on-current-change', currentRow, oldCurrentRow)
            },
            onExpand (row, status) {
                this.$emit('on-expand', row, status)
            },
            updateTableData(datas,totalCount){
                this.tableDatas = datas;
                this.pageData.total = totalCount;
                this.loading = false;
                this.sizeChanging = false;
            },
            reloadData(){
                this.loading = true;
                this.dispatcherQuery();
            },
            getCurrentData(){
                if(this.tableDatas.length>0){
                    return  this.clone(this.tableDatas[this.currentIndex]);
                }else{
                    return {};
                }
            },
            updateCurrentData(data){
                this.tableDatas[this.currentIndex] = data;
            },
            setCurrentValue(key,value) {
                (this.tableDatas[this.currentIndex])[key] = value;
            },
            resetData(){
                this.loading = true;
                this.pageData.pageNumber = 1;
                this.dispatcherQuery();
            },
            getTable(){
                return this.$refs.ruiTable;
            },
            getDicData(key){
                let column = null;
                try{
                    this.tableColumns.forEach(temp=>{
                        if(temp.key===key){
                            column = temp;
                            throw new Error('');
                        }
                    })
                }catch (e) {

                }
                if(column) {
                    if(column.globalDic){
                        return this.getDicByType(column.dicKey);
                    }
                    return column.dicData;
                }else{
                    return [];
                }
            },
            calDependIds(){
                return [this.defineId];
            },
            init(){
                this.calColumns();
                this.refComponent = this.RuiPage.makeRefs(this.refQuery);
                if(this.refComponent&&this.refComponent.$options._componentTag==='rui-query'){
                    this.refComponent.setRefComponent(this);
                }
                this.$emit('ruiTableFinished');
            }
        },
        mounted(){

        },
        watch:{
            columnsSelect:{
                handler:function(val){
                    this.calDynamicColumn();
                }
            }
        },
        beforeMount(){

        }
    }
</script>
